package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.utils.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*") // 拦截任意路径
@Slf4j
public class LoginCheckFilter implements Filter {
    //add：定义路径匹配器
    public final static AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //  log.info("拦截的路径{}", request.getRequestURI());
        // add ;
        String requestURI = request.getRequestURI();
        // 1.定义要放行的路径
        String[] infos = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        // 2.使用路径匹配器，检查要放行的路径
        boolean check = check(infos, requestURI);
        if (check) {
            filterChain.doFilter(request,response);
            return;
        }
        // 3.如果登录了也进行放行
       if ( request.getSession().getAttribute("employee") != null){

           Long empId = (Long) request.getSession().getAttribute("employee");
           //把empId保存到ThreadLocal中
           BaseContext.setCurrentId(empId);

           filterChain.doFilter(request,response);
           return;
       }
        //4-2、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }
       // 4.走其他的路径会有错误，响应字符串给前端，前端会进行路径跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] infos, String requestURI) {
        for (String info : infos) {
            boolean match = PATH_MATCHER.match(info, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
